package com.cqupt.sendMes.controller;

import cn.hutool.core.util.ObjectUtil;
import com.cqupt.sendMes.dto.UserDTO;
import com.cqupt.sendMes.entity.User;
import com.cqupt.sendMes.enums.HttpStatusEnum;
import com.cqupt.sendMes.service.UserService;
import com.cqupt.sendMes.utils.Result;
import com.cqupt.sendMes.utils.PageResult;
import com.cqupt.sendMes.vo.UserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@Api(tags = "用户相关操作")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("health")
    @ApiOperation(value = "健康检查")
    public Result<String> healthCheck(){
        return Result.createSuccessResult("服务正常");
    }

    @PostMapping("register")
    @ApiOperation(value = "用户注册")
    public Result<Boolean> register(@RequestBody @Validated UserDTO userDTO){
        return Result.createSuccessResult(userService.register(userDTO));
    }

    @PostMapping("login")
    @ApiOperation(value = "用户登录")
    public ResponseEntity<Result<String>> login(@RequestBody @Validated UserDTO userDTO){
        String token = userService.login(userDTO);
        if (ObjectUtil.isEmpty(token)){
            // 如果登录失败，返回 401 状态码
            return new ResponseEntity<>(Result.createFailResult(HttpStatusEnum.LOGIN_FAIL.getCode(), HttpStatusEnum.LOGIN_FAIL.getMessage()), HttpStatus.UNAUTHORIZED);
        }

        // 将 JWT 添加到响应头中
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", token);

        return new ResponseEntity<>(Result.createSuccessResult("登录成功"), headers, HttpStatus.OK);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "注销登录")
    public Result<Boolean> logout(){

        return Result.createSuccessResult(userService.logout());
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取用户信息")
    public Result<UserInfoVO> getUserInfo(){
        return Result.createSuccessResult(userService.getUserInfo());
    }

    @PostMapping("/list")
    @ApiOperation(value = "获取用户列表")
    public Result<PageResult<User>> getUserList(@RequestBody UserDTO userDTO){
        return Result.createSuccessResult(userService.getUserList(userDTO));
    }
}
